package com.product.service.Impl;

import com.common.VO.SupermarketResult;
import com.common.domain.Product;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.product.dao.ProductMapper;
import com.product.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author Elias
 * @version 1.0
 * @date 2021-05-12 11:17
 * @description
 * @copyright 2021
 */
@Service
public class ProductServiceImpl implements ProductService {
  @Autowired private ProductMapper productMapper;
  @Autowired private StringRedisTemplate redisTemplate;
  @Autowired private ObjectMapper objectMapper;

  @Override
  public SupermarketResult queryByPage(int page, int rows) {
    // 非框架类对象不建议从容器中拿
    int total = productMapper.selectCount();
    int start = (page - 1) * rows;
    List<Product> productList = productMapper.queryProductByPage(start, rows);
    SupermarketResult result = new SupermarketResult();
    result.setRows(productList);
    result.setTotal(total);
    return result;
  }

  @Override
  public Product queryByProductId(String productId) throws Exception {
    // TODO: 2021/5/12  使用redis缓存商品信息
    Boolean exits = null;
    try {
      exits = this.redisTemplate.hasKey("PROD_" + productId);
    } catch (Exception e) {
      //      redis未连接
      return this.productMapper.selectByPrimaryKey(productId);
    }

    if (exits == null || !exits) {
      // 如果redis中没有数据，查出来之后缓存进redis
      Product product = this.productMapper.selectByPrimaryKey(productId);
      this.redisTemplate
          .opsForValue()
          .set(
              "PROD_" + productId,
              this.objectMapper.writeValueAsString(product),
              30,
              TimeUnit.MINUTES);
      return product;
    } else {
      // 如果redis有数据，直接从redis中拿数据
      return this.objectMapper.readValue(
          this.redisTemplate.opsForValue().get("PROD_" + productId), Product.class);
    }
  }

  @Override
  public void addProduct(Product product) {
    UUID uuid = UUID.randomUUID();
    product.setProductId(String.valueOf(uuid));
    this.productMapper.insertSelective(product);
  }

  @Override
  public void updateProduct(Product product) {
    this.productMapper.updateByPrimaryKeySelective(product);
  }

  @Override
  public List<Product> queryProducts() {
    return this.productMapper.selectProducts();
  }
}
